package week12.topic11;

import com.mysql.cj.protocol.Message;
import com.mysql.cj.protocol.MessageListener;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

import java.util.Scanner;
import java.util.UUID;

/**
 * @author lfy
 */
public class ChatRoom {


    MqttClient client;
    MqttTopic topic;

    public ChatRoom(String host, String userName, String passWord, String topicName) throws MqttException {
        String clientid = UUID.randomUUID().toString();
        client = new MqttClient(host, clientid, new MemoryPersistence());

        // new mqttConnection 用来设置一些链接的属性
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置是否清空session,这里若是设置为false表示服务器会保留客户端的链接记录，这里设置为true表示每次链接到服务器都以新的身份链接
        // 换而言之，设置为false时能够客户端能够接受离线消息
        options.setCleanSession(false);
        // 设置链接的用户名和密码
        options.setUserName(userName);
        options.setPassword(passWord.toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(10);
        // 设置会话心跳时间
        options.setKeepAliveInterval(20);
        try {
            // 链接
            client.connect(options);
            // 获取activeMQ上名为TOPIC的topic
            topic = client.getTopic(topicName);
            client.subscribe(topicName, new IMqttMessageListener() {
                @Override
                public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
                    System.out.println(s + "消息:" + mqttMessage);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void publish(String msg) throws MqttPersistenceException, MqttException {
        MqttMessage message = new MqttMessage();
        //设置服务质量
        message.setQos(2);
        //设置是否在服务器中保存消息体
        message.setRetained(true);
        //设置消息的内容
        message.setPayload(msg.getBytes());
        // 发布的方法
        // new mqttDeliveryToken
        MqttDeliveryToken token = topic.publish(message);
        // 发布
        token.waitForCompletion();
        System.out.println("消息发送结果:" + token.isComplete());
    }
}
